//
//  LoginViewController.m
//  CoolFM
//
//  Created by 曹曹 on 16/8/29.
//  Copyright © 2016年 曹曹. All rights reserved.
//

#import "LoginViewController.h"
#import "TextFieldView.h"
#import "UIView+Frame.h"
#import "GX_Button.h"
#import "AFNetworking.h"
#import "NSString+GX_MD5.h"
#import "RegisterViewController.h"
#import "NSString+Regex.h"
#import "CFMacro.h"

@interface LoginViewController ()
@property (weak, nonatomic) IBOutlet GX_Button *signUp;
@property (weak, nonatomic) IBOutlet GX_Button *signIn;
@property (weak, nonatomic) IBOutlet UITextField *phoneText;
@property (weak, nonatomic) IBOutlet UITextField *passwText;
@property (nonatomic, copy) NSString *sessionID;

@end

@implementation LoginViewController

#pragma mark - LoginViewController send noti
- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [[NSNotificationCenter defaultCenter] postNotificationName:@"hidePlayerView"
                                                        object:@"playerView"
                                                      userInfo:nil];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor colorWithRed:0.97 green:0.97 blue:0.97 alpha:1.00];
    [self.navigationController setTitle:@"登录"];
    _signUp.layer.borderColor = [UIColor colorWithRed:0.11 green:0.69 blue:0.56 alpha:1.00].CGColor;
    _passwText.text = [[NSUserDefaults standardUserDefaults] objectForKey:@"password"];
    _phoneText.text = [[NSUserDefaults standardUserDefaults] objectForKey:@"contact"];
}

- (void)setIsRelogined:(BOOL)isRelogined {
    _isRelogined = isRelogined;
    _phoneText.text = _reloginUser;
    _passwText.text = @"";
}

- (void)setReloginUser:(NSString *)reloginUser {
    _reloginUser = reloginUser;
}

- (void)touchesEnded:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    [self.view endEditing:YES];
}

#pragma mark - 注册点击事件
- (IBAction)goSignUp:(id)sender {
    RegisterViewController *registVC = [[RegisterViewController alloc] init];
    UIButton *button = (UIButton *)sender;
    if (button.tag == 1000 ) {
        registVC.isFogetPassword = YES;
    }
    [self.navigationController pushViewController:registVC animated:YES];
}

#pragma mark - 登录点击事件
- (IBAction)goSignIn:(id)sender {
    if ([_phoneText.text isEqualToString:@""]) {
        [self addPromptLabelWithTitle:@"手机号不能为空"];
        return;
    }
    if (![NSString valiMobile:_phoneText.text]) {
        [self addPromptLabelWithTitle:@"手机号为6-11为数字"];
        return;
    }
    if ([_passwText.text isEqualToString:@""]) {
        [self addPromptLabelWithTitle:@"密码不能为空"];
        return;
    }
    if (_passwText.text.length < 6) {
        [self addPromptLabelWithTitle:@"密码为6-16位的数字或字母"];
        return;
    }
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.requestSerializer = [AFJSONRequestSerializer serializer];
    [manager.requestSerializer setQueryStringSerializationWithBlock:^NSString * _Nonnull(NSURLRequest * _Nonnull request, id  _Nonnull parameters, NSError * _Nullable __autoreleasing * _Nullable error) {
        return parameters;
    }];
    NSString *MD5Pass = [_passwText.text MD5String32BitsLowercase];
    NSDictionary *longin = @{@"password":MD5Pass,
                             @"version":@"4.4.0",
                             @"user_ip":@"127.0.0.1",
                             @"contact": _phoneText.text};
    
    [manager.requestSerializer setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
    [manager.requestSerializer setValue:@"111" forHTTPHeaderField:@"Content-Length"];
    [manager.requestSerializer setValue:@"api.kufm.cn" forHTTPHeaderField:@"Host"];
    [manager.requestSerializer setValue:@"ios/4.3.0.0.0/appstore/release" forHTTPHeaderField:@"X-API-ID"];
    [manager.requestSerializer setValue:@"d0ce47483e6728610311619cca3fb195" forHTTPHeaderField:@"X-APP-ID"];
    
    [manager POST:@"http://api.kufm.cn/v2/user/login"
       parameters:longin
         progress:^(NSProgress * _Nonnull uploadProgress) {
             
         } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
             NSLog(@"responseObject:%@", responseObject);
             _sessionID = [responseObject[@"data"] objectForKey:@"session_id"];
             NSDictionary *userDictionary = @{@"user_id": [responseObject[@"data"] objectForKey:@"user_id"],
                                              @"error_code":responseObject[@"error_code"],
                                              @"session_id":[responseObject[@"data"] objectForKey:@"session_id"]};
             /**
              * 1.登录成功后保存用户信息
              */
             NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
             [user setObject:_phoneText.text forKey:@"contact"];
             [user setObject:_passwText.text forKey:@"password"];
             [user setObject:[responseObject[@"data"] objectForKey:@"session_id"] forKey:@"session_id"];
             [user setBool:YES forKey:@"login"];
             /**
              * 这里需要给初次注册登录的账号一个创建时间
              */
             [user setObject:@"2016-08-25" forKey:@"create_at"];
             /**
              * 发送消息--登陆成功
              */
             [[NSNotificationCenter defaultCenter] postNotificationName:@"login"
                                                                 object:@"login"
                                                               userInfo:userDictionary];
             [self.navigationController popToRootViewControllerAnimated:YES];
         } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
             [self addPromptLabelWithTitle:@"密码错误,请重新输入"];
             return;
         }];
}
#pragma mark - 添加提示条动画
- (void)addPromptLabelWithTitle:(NSString *)title {
    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, -20, self.view.gx_width, 20)];
    label.text = title;
    label.textColor = [UIColor whiteColor];
    label.textAlignment = NSTextAlignmentCenter;
    label.font = [UIFont systemFontOfSize:12];
    label.gx_centerX = self.view.gx_centerX;
    label.backgroundColor = [UIColor grayColor];
    [self.view addSubview:label];
    // 出现
    [UIView animateWithDuration:0.5 animations:^{
        label.gx_y = 0;
        // 显示2秒
    } completion:^(BOOL finished) {
        [UIView animateWithDuration:0.5 delay:2 options:UIViewAnimationOptionCurveLinear animations:^{
            label.gx_y = -20;
        } completion:^(BOOL finished) {
            [label removeFromSuperview];
        }];
    }];
}

- (void)getSessionID:(NSString *)sessionID {
    if (self.delegate && [self.delegate respondsToSelector:@selector(getSessionID:)]) {
        [self.delegate getSessionID:_sessionID];
    }
}

@end
